package com.example.dictdemo.validator;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;

import com.example.dictdemo.model.vo.DictModel;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;

/**
 * 数据字段自定义验证，用于验证Model中关联的常量字典值的合法性。
 *
 * @author dlp
 * @date 2024-07-02
 */
@Slf4j
public class ConstDictValidator implements ConstraintValidator<ConstDictRef, Object> {

  public static final String IS_VALID = "isValid";
  private ConstDictRef constDictRef;

  @Override
  public void initialize(ConstDictRef constDictRef) {
    this.constDictRef = constDictRef;
  }


  @Override
  public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
    if (ObjectUtil.isEmpty(value)) {
      return true;
    }
    try {
      Class<?> clazz = constDictRef.constDictClass();
      if (clazz.getFields().length > 0) {
        Field field = clazz.getFields()[0];
        // 确保这是一个枚举常量
        if (field.isEnumConstant()) {
          // 获取字段（枚举常量）实例
          Object enumInstance = field.get(null);
          // 调用 isValid 方法
          Method method = clazz.getDeclaredMethod(IS_VALID,String.class);
          if (value instanceof Integer) {
            value = String.valueOf(value);
          }
          return ReflectUtil.invoke(enumInstance,method, value);
        }
      }
      return false;
    } catch (NoSuchMethodException | IllegalAccessException e) {
      log.error("校验枚举合法性异常",e);
      return false;
    }
  }
}
